﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Library.Repository;
using Library.TwiCommunication;

namespace Library.Utils
{


    public class ServiceLocator : IServiceLocator
    {
        private IDictionary<object, object> _services;

        private ServiceLocator()
        {
            _services = new Dictionary<object, object>();

            _services.Add(typeof(IUserRepository), new UserRepository());
            _services.Add(typeof(IDeviceRepository), new DeviceRepository());
            
            if(UserRepository.IsLinux) _services.Add(typeof(ITwiCommunicator), new TwiCommunicator());
            else _services.Add(typeof(ITwiCommunicator), new TwiCommunicatorMock());            //TODO: Sprawdzić, czy mock działa
        }

        public static IServiceLocator Instance
        {
            get
            {
                lock(TheLock)
                {
                    if(_instance == null) _instance = new ServiceLocator();
                }
                return _instance;
            }
        }

        private static IServiceLocator _instance;

        private static readonly object TheLock = new Object();


        public T GetService<T>()
        {
            try
            {
                return (T) _services[typeof (T)];
            }
            catch (Exception)
            {
                throw new ApplicationException("Żądany serwis (" + typeof(T) +") nie jest zarejestrowany");
            }
        }
    }




    public interface IServiceLocator
    {
        T GetService<T>();
    }
}
